const path = require('path')
const { defineConfig, build } = require('vite')
const vue = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')
const fsExtra = require('fs-extra')
const fs = require('fs')

// 打包入口文件夹
const entryDir = path.resolve(__dirname, '../src/components/lib')
// 打包出口文件夹
const outDir = path.resolve(__dirname, '../lib')

const baseConfig = defineConfig({
  configFile: false,
  publicDir: false,
  plugins: [vue(), vueJsx()]
})

const rollupOptions = {
  external: ['vue'],
  output: {},
  globals: {
    vue: 'Vue'
  }
}

const buildAll = async () => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, 'index.ts'),
        name: 'sps-antd-components',
        fileName: 'index',
        formats: ['es', 'umd']
      },
      outDir
    }
  })
}

const buildSingle = async (name) => {
  await build({
    ...baseConfig,
    build: {
      rollupOptions,
      lib: {
        entry: path.resolve(entryDir, name),
        name: 'index',
        fileName: 'index',
        formats: ['es', 'umd']
      },
      outDir: path.resolve(outDir, name)
    }
  })
}

const createPackageJson = (name, filePath) => {
  const fileStr = `
  {
    "name": "${name}",
    "main": "index.umd.js",
    "module": "index.es.js",
    "style": "styles.css"
  }`

  fsExtra.outputFile(path.resolve(outDir, filePath), fileStr, 'utf-8')
}

const buildLib = async () => {
  await buildAll()
  createPackageJson('sps-components', 'package.json')

  const components = fs.readdirSync(entryDir).filter((name) => {
    const componentDir = path.resolve(entryDir, name)
    const isDir = fs.lstatSync(componentDir).isDirectory()
    return (
      isDir &&
      name !== 'utils' &&
      fs.readdirSync(componentDir).includes('index.ts')
    )
  })

  for (const name of components) {
    await buildSingle(name)
    createPackageJson(name, `${name}/package.json`)
  }
}

buildLib()
